package com.ysd.lis.service.lab.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.SysInterface;
import com.ysd.lis.entity.SysOrganization;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.bac.BacSiteOfInfectionDict;
import com.ysd.lis.entity.lab.LabSampleType;
import com.ysd.lis.mapper.lab.LabSampleTypeMapper;
import com.ysd.lis.mapper.sys.SysBasDictDetailMapper;
import com.ysd.lis.mapper.sys.SysBasDictMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.mapper.sys.SysOrganizationMapper;
import com.ysd.lis.request.AddSampleTypeParam;
import com.ysd.lis.request.SampleTypePageParam;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.lab.LabSampleTypeService;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Cfz
 * @since 2023-12-13
 */
@Service
@Component
public class LabSampleTypeServiceImpl extends ServiceImpl<LabSampleTypeMapper, LabSampleType> implements LabSampleTypeService {

    @Autowired
    private LabSampleTypeMapper labSampleTypeMapper;
    @Autowired
    SysOrganizationMapper sysOrganizationMapper;
    @Autowired
    private SysBasDictDetailMapper basDictDetailMapper;
    @Autowired
    private SysBasDictMapper basDictMapper;
    @Autowired
    private SysBasDictDetailService sysBasDictDetailService;
    @Autowired
    SysInterfaceMapper sysInterfaceMapper;

    @Override
    public Result findLabSampleTypeList(SampleTypePageParam SampleTypePageParam) {
        MPJLambdaWrapper<LabSampleType> lambdaQueryWrapper = new MPJLambdaWrapper();
        lambdaQueryWrapper.selectAll(LabSampleType.class);
        lambdaQueryWrapper.selectAs(BacSiteOfInfectionDict::getName, LabSampleType::getInfectSiteNa);
        lambdaQueryWrapper.leftJoin(BacSiteOfInfectionDict.class, it->it.eq(BacSiteOfInfectionDict::getCode, LabSampleType::getInfectSiteNo).eq(BacSiteOfInfectionDict::getDelFlag, 0));
        lambdaQueryWrapper.eq(LabSampleType::getDelFlag, 0);
        if (StrUtil.isNotEmpty(SampleTypePageParam.getKeyWords())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabSampleType::getSampleTypeCode, SampleTypePageParam.getKeyWords()).or().like(LabSampleType::getSampleTypeName, SampleTypePageParam.getKeyWords()).or().like(LabSampleType::getInputCode, SampleTypePageParam.getKeyWords()));
        }
        if(ToolsUtils.isNotEmpty(SampleTypePageParam.getFilter())){
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabSampleType::getSampleTypeCode, SampleTypePageParam.getFilter()).or().like(LabSampleType::getSampleTypeName, SampleTypePageParam.getFilter()).or().like(LabSampleType::getInputCode, SampleTypePageParam.getFilter()));
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(SampleTypePageParam.getOrgId()), LabSampleType::getOrgId, SampleTypePageParam.getOrgId());

        List<LabSampleType> labSampleTypes = labSampleTypeMapper.selectList(lambdaQueryWrapper);

        if (ToolsUtils.isNotEmpty(labSampleTypes)) {
            //批量获取组织机构
            List<String> orgIds = labSampleTypes.stream().filter(lab -> ToolsUtils.isNotEmpty(lab.getOrgId())).map(LabSampleType::getOrgId).distinct().collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(orgIds)) {
                List<SysOrganization> sysOrganizations = sysOrganizationMapper.selectBatchIds(orgIds);
                for (LabSampleType item : labSampleTypes) {
                    if (ToolsUtils.isNotEmpty(item.getOrgId())) {
                        Optional<SysOrganization> first = sysOrganizations.stream().filter(o -> o.getId().equals(item.getOrgId())).findFirst();
                        if (first.isPresent()) {
                            SysOrganization orgEntry = first.get();
                            item.setOrgCode(ToolsUtils.isNotEmpty(orgEntry) && ToolsUtils.isNotEmpty(orgEntry.getCode()) ? orgEntry.getCode() : "");
                            item.setOrgName(ToolsUtils.isNotEmpty(orgEntry) && ToolsUtils.isNotEmpty(orgEntry.getName()) ? orgEntry.getName() : "");
                        }
                    }
                }

            }
            //for (LabSampleType item : labSampleTypes) {
//                if (ToolsUtils.isNotEmpty(item.getOrgId())) {
//                    SysOrganization orgEntry = sysOrganizationService.getById(item.getOrgId());
//                    item.setOrgCode(ToolsUtils.isNotEmpty(orgEntry) && ToolsUtils.isNotEmpty(orgEntry.getCode()) ? orgEntry.getCode() : "");
//                    item.setOrgName(ToolsUtils.isNotEmpty(orgEntry) && ToolsUtils.isNotEmpty(orgEntry.getName()) ? orgEntry.getName() : "");
//                }

//                if (ToolsUtils.isNotEmpty(item.getSampleTypeId())) {
//                    LambdaQueryWrapper<SysBasDictDetail> basDictDetailWrapper = new LambdaQueryWrapper<>();
//                    basDictDetailWrapper.eq(SysBasDictDetail::getDelFlag, "0").eq(SysBasDictDetail::getCode, "name").eq(SysBasDictDetail::getCommonId, item.getSampleTypeId());
//                    List<SysBasDictDetail> basDictDetails = basDictDetailMapper.selectList(basDictDetailWrapper);
//                    if (ToolsUtils.isNotEmpty(basDictDetails)) {
//                        item.setSampleTypeName(!basDictDetails.isEmpty() && ToolsUtils.isNotEmpty(basDictDetails.get(0).getValue()) ? basDictDetails.get(0).getValue() : "");
//                    }
//                    basDictDetailWrapper = new LambdaQueryWrapper<>();
//                    basDictDetailWrapper.eq(SysBasDictDetail::getDelFlag, "0").eq(SysBasDictDetail::getCode, "code").eq(SysBasDictDetail::getCommonId, item.getSampleTypeId());
//                    List<SysBasDictDetail> basDictDetails1 = basDictDetailMapper.selectList(basDictDetailWrapper);
//                    if (ToolsUtils.isNotEmpty(basDictDetails1)) {
//                        item.setSampleTypeCode(!basDictDetails1.isEmpty() && ToolsUtils.isNotEmpty(basDictDetails1.get(0).getValue()) ? basDictDetails1.get(0).getValue() : "");
//                    }
//                }
            //}
        }

        return Result.succ(1, "查询成功！", labSampleTypes);
    }

    @Override
    public Result addSampleType(AddSampleTypeParam addSampleTypeParam) {
        LabSampleType labSampleType = new LabSampleType();
        BeanUtil.copyProperties(addSampleTypeParam, labSampleType);
        SysUser sysUser = RedisUserManager.getUser();
        if (ToolsUtils.isNotEmpty(sysUser)) {
            sysUser.setOrgId(sysUser.getOrgId());
        }
        boolean save = this.save(labSampleType);

        if (save) {
            return Result.succ(1, "添加成功！", null);
        } else {
            return Result.fail("添加失败！");
        }
    }

    @Override
    public Result editSampleType(AddSampleTypeParam addSampleTypeParam) {
        LabSampleType labSampleType = new LabSampleType();
        BeanUtil.copyProperties(addSampleTypeParam, labSampleType);
        SysUser sysUser = RedisUserManager.getUser();
        if (ToolsUtils.isNotEmpty(sysUser)) {
            sysUser.setOrgId(sysUser.getOrgId());
        }
        boolean b = this.updateById(labSampleType);
        if (b) {
            return Result.succ(1, "编辑成功！", null);
        } else {
            return Result.fail("编辑失败！");
        }
    }

    @Override
    public Result deleteSampleType(AddSampleTypeParam addSampleTypeParam) {
        LabSampleType labSampleType = new LabSampleType();
        BeanUtil.copyProperties(addSampleTypeParam, labSampleType);
        labSampleType.setDelFlag(1);
        boolean b = this.updateById(labSampleType);
        if (b) {
            return Result.succ(1, "删除成功！", null);
        } else {
            return Result.fail("删除失败！");
        }
    }

    /*同步标本类型*/
    @Override
    public Result syncSampleType() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        String orgId = RedisUserManager.getStoreOrg("currentOrg" + token);

        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());

        try {
            if (CollectionUtils.isNotEmpty(collect)) {
                for (String webUrl : collect) {
                    LabSampleType q = new LabSampleType();
                    q.setOrgId(orgId);
                    String returnMsg = HttpUtil.createPost(webUrl + "/public/SyncLabSampleType").body(JSONUtil.toJsonStr(q)).contentType("application/json").execute().body();
                    JSONObject reportObject = new JSONObject(returnMsg);
                    JSONObject reportStatus = reportObject.getJSONObject("status");
                    String reportCode = reportStatus.get("code").toString();
                    if ("400".equals(reportCode)) {
                        return Result.fail("接口管理平台异常,请检查");
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("接口管理平台异常,请检查");
        }

        return Result.succ(1, "操作成功", null);
    }

    @Override
    public LabSampleType findOneByNo(String no) {
        if (StringUtils.isBlank(no)) {
            return null;
        }
        LambdaQueryWrapper<LabSampleType> query = new LambdaQueryWrapper<>();
        query.eq(LabSampleType::getDelFlag, 0);
        query.eq(LabSampleType::getSampleTypeCode, no);
        List<LabSampleType> lst = labSampleTypeMapper.selectList(query);
        if (!lst.isEmpty()) {
            return lst.get(0);
        }
        return null;
    }
}
